<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

class m_backoffice_documents_Folder extends m_backoffice_documents_FolderBase
{
    const IMAGES_ROOT = "images";
    
	/**
	 * @return m_backoffice_documents_Folder
	 */
	public static function createNew()
	{
		return new self();
	}
	
	/**
	 * @return m_backoffice_documents_Folder
	 */
	public static function getInstanceByUniqueId($id, $lang = null)
	{
		if(is_null($lang)) $lang = f_core_Context::getInstance()->getLang();
		$cache = f_core_Cache::getInstance();
		
		$key = $cache->getDocumentCacheKey($id, $lang);
		
		if($cache->hasCache($key))
		{
			return $cache->getCacheContent($key);
		}
		
		$object = new self($id, $lang);
		
		$cache->putInCache($key, $object);
		
		return $object;
	}
	
	/**
	 * Magic PHP5 method to simulate add and get
	 *
	 * @param string $method
	 * @param mixed $attr
	 * @return mixed
	 */
	public function __call($method, $attr)
	{
		$prefix = substr($method, 0, 3);
		$suffix = strtolower(substr($method, 3));

        $attr[0] = isset($attr[0]) ? $attr[0] : null;
        $attr[1] = isset($attr[1]) ? $attr[1] : null;
        $attr[2] = isset($attr[2]) ? $attr[2] : null;

        $relationManager = f_relation_ManagerNew::getInstance($this);

		if($prefix == "add")
		{
            $relationOrder = null;
            if(isset($attr[1])) $relationOrder = $attr[1];
			$relationManager->addRelation($attr[0], $suffix);
			return $this;
		}
		else if($prefix == "get")
		{
			if(substr($suffix, -2, 2) == "nb")
			{
				return $relationManager->getChilds()->withRelationType(substr($suffix, 0, -2))->withLang($this->getLang())->count();
			}

            $nbResults = $attr[0];
            $offset = $attr[1];
            $order = $attr[2];

			return $relationManager->getChilds()->withRelationType($suffix)->withLang($this->getLang())->limit($nbResults, $offset)->orderBy('ASC')->retrieveDocuments();
		}		
	}

	/**
	 * Delete the medias folder if exist
	 */
	protected function preDelete()
	{
        $dirPath = $this->getFolderPath();

        if(is_dir($dirPath))
        {
            $this->deleteSubFolder($dirPath);
        }
	}

    private function deleteSubFolder($path)
    {
        $folder = f_file_Directory::getInstance($path);
        $subFolders = $folder->getSubdirs();

        if(!empty($subFolders) && is_array($subFolders))
        {
            foreach($subFolders as $subFolder)
            {
                $files = $subFolder->getFiles();
                if(!empty($files) && is_array($files))
                {
                    foreach($files as $file)
                    {
                        @unlink($file->getFile());
                    }
                }

                $this->deleteSubFolder($subFolder->getPath());
            }
        }
        
        return @rmdir($path);
    }

    private function getFolderPath()
    {
        $filePath = HTTP_DIR.DS.self::IMAGES_ROOT;

        if(is_dir($filePath))
        {
            $parents = f_relation_ManagerNew::getInstance($this)->getParents()->withModel($this->getModel())->retrieveIdsAndModels();
            $tab = array();
            if(!is_null($parents))
            {
                foreach($parents as $parent)
                {
                    $tab[] = $parent['id'];
                }
            }

            $tab[] = $this->getUniqueId();

            $filePath .= DS . implode(DS, $tab);

            return $filePath;
        }

        return false;
    }
	
	/**
	 * Method to indicate if folder can slide in left menu
	 *
	 * @return boolean
	 */
	public function canSlide()
	{
		return true;
	}
	
	/**
	 * Get folder icon from treeFolder.xml file in module folder
	 * @return string
	 */
	public function getIcon()
	{
		$moduleName = $this->getModule();
		
		$xmlFile = MODULES_DIR.DS.$moduleName.DS."config".DS."treeFolder.xml";
		
		if(is_file($xmlFile))
		{
			$xml = f_xml_Xpath::getInstance($xmlFile)->fromXpath("params")->getAttributes();
			return $xml["icon"];
		}
		return "";
	}

    public function getDocumentModuleName()
    {
        return $this->getModule();
    }
	
	/**
	 * Returns the folder edition url specified in treeFolder.xml in module folder
	 *
	 * @param string $lang
	 * @param array $parameters
	 * @return string
	 */
	public function getEditUrl($lang = null, $parameters = null)
	{
		$moduleName = $this->getModule();
		
		$xmlFile = MODULES_DIR.DS.$moduleName.DS."config".DS."treeFolder.xml";
		
		if(is_file($xmlFile))
		{
			$xml = f_xml_Xpath::getInstance($xmlFile)->fromXpath("params")->getAttributes();
			
			if(is_null($lang)) $lang = $this->getLang();
			
			$params = array("docLang" => strtolower($lang), "docId" => $this->getUniqueId(), "configModule" => $moduleName);			
			
			if(is_array($parameters) && count($parameters) >= 1)
			{
				$params = array_merge($params, $parameters);
			}
			
			return f_core_Routing::getUrl($xml["route"], $params);
		}
		return "";
	}
	
	/**
	 * Return the current folder delete url
	 *
	 * @param string $lang
	 * @return string
	 */
	public function getDeleteUrl($lang = null)
	{
		$moduleName = $this->getModule();
		
		$xmlFile = MODULES_DIR.DIRECTORY_SEPARATOR.$moduleName.DIRECTORY_SEPARATOR."config".DIRECTORY_SEPARATOR."treeFolder.xml";
		
		if(is_file($xmlFile))
		{
			$xml = f_xml_Xpath::getInstance($xmlFile)->fromXpath("params")->getAttributes();
			
			if(is_null($lang)) $lang = $this->getLang();
			
			$params = array("docLang" => strtolower($lang), "docId" => $this->getUniqueId(), "configModule" => $moduleName);			
			
			if(isset($parameters) && is_array($parameters) && count($parameters) >= 1)
			{
				$params = array_merge($params, $parameters);
			}
			
			return f_core_Routing::getUrl($xml["deleteRoute"], $params);
		}
		return "";		
	}

	/**
	 * Get all related fields
	 *
	 * @return array
	 */
	public function relationFields()
	{
		$dbProvider = f_database_Provider::getInstance();
		
		$relationFields = $dbProvider	->setQuery("SELECT `relation_type` FROM `f_relation` WHERE `child_id`=:docId OR `parent_id`=:docId")
										->execute(array("docId" => $this->getUniqueId()))
										->getQueryResults(PDO::FETCH_COLUMN);

		return array_unique($relationFields);
	}
	
	/**
	 * Check if folder is targetable or not
	 * 
	 * @see codizer/document/f_document_baseDocument#isTargetable()
	 */
	public function isTargetable()
	{
		$targets = f_target_Manager::getInstance()->setModule($this->getModule())->setDocument($this)->getTargets();

		return count($targets) > 0;
	}

    public function getBoSearchIcon()
    {
        return m_medias_services_MediaService::getInstance()->getIconPath($this->getIcon());
    }
}